﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HtmlAgilityPack;
using ObservadorPeplau.API.Business;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;

namespace ObservadorPeplau.API.DAL
{
    internal class HomepageDAO
    {
        private readonly HtmlWeb _htmlWeb;
        private HtmlDocument _htmlDocument;

        public HomepageDAO()
        {
            _htmlWeb = new HtmlWeb();
            _htmlDocument = null;
        }

        #region Public Methods

        public void LoadHomePage()
        {
            _htmlDocument = _htmlWeb.Load(Constants.HomePageUrl);
        }

        public List<Discussion> GetFeaturedDiscussions()
        {
            if (_htmlDocument==null)
                LoadHomePage();
            if (_htmlDocument == null)
                return new List<Discussion>();

            // Get main Section Node
            var dlNode = _htmlDocument.DocumentNode.SelectSingleNode("//section[@id='featured-debates']/dl");
            if (dlNode == null)
                return new List<Discussion>();

            return GetDiscussionsFromSection(dlNode);
        }

        public List<Discussion> GetNewDiscussions()
        {
            if (_htmlDocument == null)
                LoadHomePage();
            if (_htmlDocument == null)
                return new List<Discussion>();

            // Get main Section Node
            var dlNode = _htmlDocument.DocumentNode.SelectSingleNode("//section[@id='new-debates']/dl");
            if (dlNode == null)
                return new List<Discussion>();

            return GetDiscussionsFromSection(dlNode);
        }
        #endregion

        #region Private Methods
        private List<Discussion> GetDiscussionsFromSection(HtmlNode dlNode)
        {
            var lstRet = new List<Discussion>();

            // Get DT and DD pairs 
            var dtCollection = dlNode.SelectNodes("dt");
            var ddCollection = dlNode.SelectNodes("dd");

            // Loop to create Discussion instances
            for (int i = 0; i < dtCollection.Count; i++)
            {
                var dtNode = dtCollection[i];
                var ddNode = ddCollection[i];

                if (dtNode == null || ddNode == null)
                    continue;

                // Create new Discussion object
                var newDiscussion = new Discussion();
                lstRet.Add(newDiscussion);

                // Discussion
                newDiscussion.Title = dtNode.SelectSingleNode("a").InnerText;
                newDiscussion.Url = dtNode.SelectSingleNode("a").Attributes["href"].Value;

                // Author
                newDiscussion.Author = new Author();
                newDiscussion.Author.ImageUrl = dtNode.SelectSingleNode("img").Attributes["src"].Value;
                newDiscussion.Author.Login = ddNode.SelectSingleNode("a[1]").InnerText;

                // DateTime
                var startIndex = ddNode.InnerText.IndexOf(", em") + 5;
                var stringLength = ddNode.InnerText.LastIndexOf(",") - startIndex;
                var dateTimePart = ddNode.InnerText.Substring(startIndex, stringLength).Replace("às ", "");
                var datePart = dateTimePart.Split(' ')[0];
                var hourPart = dateTimePart.Split(' ')[1];
                var day = int.Parse(datePart.Split('/')[0]);
                var mon = int.Parse(datePart.Split('/')[1]);
                var yea = int.Parse(datePart.Split('/')[2]);
                var hou = int.Parse(hourPart.Split(':')[0]);
                var min = int.Parse(hourPart.Split(':')[1]);
                newDiscussion.DateTime = new DateTime(yea,mon,day,hou,min,0);

                // Comments
                var strNumberOfComments = ddNode.SelectSingleNode("a[last()]").InnerText.Replace("comentários", "").Trim();
                strNumberOfComments = strNumberOfComments.Replace("comentário", "").Trim();
                var numberOfComments = strNumberOfComments == "comente" ? 0 : int.Parse(strNumberOfComments);

                newDiscussion.NumberOfComments = numberOfComments;
            }

            return lstRet;
        }
        #endregion
    }
}
